<?php
namespace app\api\controller;

use app\api\common\controller\Api;
use think\cache\driver\Redis;
use think\facade\Db;
use think\facade\Request;
use app\admin\model\SystemAdmin;
use think\facade\Cache;
use think\facade\Config;
use app\api\model\StoreLogin as storeLoginModel;

class Login
{
    private $admin_id = 0;
    public function login(){
        $post = Request::param();
        //$post['username'] = 'admin';
        //$post['password'] = '123456';
        $admin = SystemAdmin::where(['username' => $post['username']])->find();
        if (empty($admin)) {
            return show(-2,'用户不存在',[]);
        }
        if (password($post['password']) != $admin->password) {
            return show(-1,'密码输入有误',[]);   
        }
        if ($admin->status == 0) {
            return show(0,'账号已被禁用',[]);
        }
        $this->admin_id = $admin->id;
        $login = $this->loginInfo();
        return show('one','',$login);

        
        
        
    }
    private function loginInfo(){
        $redis = Cache::store('redis');
        $key = Config::get('token.key');
        $str = Config::get('token.str').'||'.$this->admin_id;
        // halt($str);
        $token = authcode($str,'ENCODE',$key,0); //加密
        $user_id = Config::get('token.storeprefix')."-".$this->admin_id;
        $expire = Config::get('token.expire');
        $redis->set($user_id,$token,$expire);
          $info = Db::name('system_admin') -> field('head_img,username,phone,remark,id,source')->where('id',$this->admin_id) -> find();
        $data = [
            "accessToken" => $token,
            "tokenExpired" => $expire,
            "info" => $info
    	];
        return $data;

    }
    
    
}